<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true">
                <el-form-item>
                    <el-button type="primary" icon="plus" size="large" style="width: 200px"  @click="adminAdd" v-show="addButton">添加管理员</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="adminers" highlight-current-row v-loading="listLoading"
                  style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column label="ID" prop="id" width="80">
            </el-table-column>
            <el-table-column prop="username" label="用户名">
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="180">
            </el-table-column>
            <el-table-column prop="status" label="状态" :formatter="formatStatus" width="100">
            </el-table-column>
            <el-table-column label="注册时间" prop="regtime">
            </el-table-column>
            <el-table-column label="登录时间" prop="logintime">
            </el-table-column>
            <el-table-column label="登录IP" prop="loginip">
            </el-table-column>
            <el-table-column label="操作" width="300">
                <template slot-scope="scope">
                    <el-button size="small" @click="editAdminerInfo(scope.$index, scope.row)" type="primary" v-show="editInfoButton">编辑信息</el-button>
                    <el-button size="small" @click="editAdminerPurview(scope.$index, scope.row)" type="info" v-show="editPurviewButton">分配权限</el-button>
                    <el-button type="danger" size="small" @click="delAdminer(scope.$index, scope.row)" icon="delete" v-show="deleteButton">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--新增界面-->
        <el-dialog title="新增管理员" v-model="addAdminer" :close-on-click-modal="false" style="width:1000px;margin: 0 auto;">
            <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="addForm.username" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="addForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="工号" prop="work_uid">
                    <el-input v-model="addForm.work_uid" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addAdminer = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--编辑界面-->
        <el-dialog title="编辑个人资料" v-model="editFormInfoVisible" :close-on-click-modal="false" style="width:1000px;margin: 0 auto;">
            <el-form :model="editInfoForm" label-width="80px" :rules="addFormRules" ref="editInfoForm">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="editInfoForm.username" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="editInfoForm.password" auto-complete="off" placeholder="*******"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="editInfoForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="工号" prop="work_uid">
                    <el-input v-model="editInfoForm.work_uid" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch v-model="editInfoForm.status" on-color="#13ce66" off-color="#ff4949" on-value="1" off-value="0"></el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editInfoSubmit(editInfoForm.id)" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--编辑权限界面-->
        <el-dialog title="编辑权限" v-model="editFormVisible" :close-on-click-modal="false" style="margin-top: 100px;">
            <el-form label-width="80px" ref="editForm">
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="purviewCheckAllChange">全选</el-checkbox>
                <div style="margin: 15px 0;" ref="checkPurDiv"></div>
                <el-checkbox-group v-model="checkedPurview" @change="purviewCheckedChange">
                    <el-checkbox v-for="(pur, key) in purviewName" :label="pur" :key="key" style="margin-right: 10px;margin-top: 10px;" ref="checkPurbox">{{ pur }}</el-checkbox>
                </el-checkbox-group>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="success" @click.native="editPurviewSubmit" :loading="editLoading">确认修改</el-button>
            </div>
        </el-dialog>

    </section>
</template>

<script type="text/ecmascript-6">
  import util from '../util'
  import { isUrlHasPurview } from '../vuex/getters'
  import { tree, apiTree } from '../apiTree'

  export default {
    data() {
      return {
        checkAll: true,
        adminers: [],
        editLoading: false,
        checkedPurview: [],
        addAdminer: false,
        addLoading: false,
        listLoading: false,
        editFormInfoVisible: false,
        editFormVisible: false,
        isIndeterminate: true,
        purviewTree: {},
        name_pur: {},
        addFormRules: {
          'username': [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
          ],
          'password': [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
          ],
          'name': [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ]
        },
        globalPurview: [],
        purviewList: [],
        purviewName: [],
        editedValue: [],
        id: 0,
        Tindex: 0,
        // 编辑管理员资料
        editInfoForm: {
          id: 0,
          name: '',
          password: '',
          username: '',
          work_uid: 0,
          status: 1
        },
        // 新增界面数据
        addForm: {
          name: '',
          password: '*******',
          username: 'kkfarm_',
          work_uid: 0
        }
      }
    },
    methods: {
      // 状态显示
      formatStatus(row, column) {
        return row.status === '1' ? '正常' : row.status === '0' ? '锁定' : '未知'
      },
      // 全选
      purviewCheckAllChange(event) {
        this.checkedPurview = event.target.checked ? this.purviewName : []
        this.isIndeterminate = false
      },
      // 全部选中时候，再选中全选
      purviewCheckedChange(value) {
        console.log(value);
        let checkedCount = value.length
        this.checkAll = checkedCount === this.purviewName.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.purviewName.length
      },
      // 编辑管理员个人信息
      editAdminerInfo(index, row) {
        this.editFormInfoVisible = true
        this.editInfoForm = {
          id: row.id,
          name: row.name,
          password: '**********',
          username: row.username,
          status: row.status,
          work_uid: row.work_uid
        }
      },
      // 编辑个人资料提交
      editInfoSubmit() {
        this.$refs.editInfoForm.validate((valid) => {
          if (valid) {
            this.addLoading = true
            let param = util.cloneObj(this.editInfoForm)
            delete param.id;
            let params = {'data': param};
            params.id = this.editInfoForm.id;
            apiTree('adminer/edit', 'adminer/edit', params, 'POST').then((res) => {
              this.addLoading = false
              if (res.s === 1) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.$refs['editInfoForm'].resetFields()
                this.editFormInfoVisible = false
                this.getAdminers()
              }
            })
          }
        })
      },
      // 编辑管理员权限
      editAdminerPurview(index, row) {
        this.Tindex = index
        this.id = row.id
        this.editFormVisible = true
        this.checkedPurview = []
        // 设置选中的权限
        for (let i in row.purview) {
          if (!util.isEmpty(row.purview[i].name)) {
            this.checkedPurview.push(row.purview[i].name)
          }
        }
      },
      //  提交编辑的权限
      editPurviewSubmit() {
        let param = {}
        for (let i = 0; i < this.$refs.checkPurbox.length; i++) {
          if (this.$refs.checkPurbox[i].isChecked) {
            param[this.purviewList[i]] = this.purviewTree[this.purviewList[i]]
          }
        }
        let params = {'data[purview]': JSON.stringify(param)}
        params.id = this.id;
        apiTree('adminer/editPurview', 'adminer/edit', params, 'POST').then((res) => {
          this.addLoading = false
          if (res.s === 1) {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.editFormVisible = false
            this.getAdminers();
          }
        })
      },
      // 添加管理员
      adminAdd() {
        this.addAdminer = true
      },
      addSubmit() {
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            this.addLoading = true
            let param = this.addForm
            apiTree('adminer/add', 'adminer/add', param).then((res) => {
              this.addLoading = false
              // NProgress.done()
              if (res.s === 1) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.$refs['addForm'].resetFields()
                this.addAdminer = false
                this.getAdminers()
              }
            })
          }
        })
      },
      // 删除管理员
      delAdminer(index, row) {
        this.$confirm('确认删除该管理员吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          let param = {id: row.id}
          apiTree('adminer/delete', 'adminer/delete', param).then((res) => {
            this.listLoading = false
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getAdminers()
          })
        }).catch(() => {
          this.$message({
            message: '删除失败',
            type: 'warning'
          })
        })
      },
      // 获得管理员列表
      getAdminers() {
        this.listLoading = true
        apiTree('adminer/index', 'adminer/index', {}).then((res) => {
          res.d.data.forEach((data, key) => {
            if (data.purview) {
              res.d.data[key]['purview'] = JSON.parse(data.purview)
            }
            res.d.data[key]['regtime'] = util.formatDate.format(new Date(data.regtime * 1000), 'yyyy-MM-dd hh:mm:ss')
            if (data.logintime) {
              res.d.data[key]['logintime'] = util.formatDate.format(new Date(data.logintime * 1000), 'yyyy-MM-dd hh:mm:ss')
            }
          })
          this.total = res.d.total_num
          this.adminers = res.d.data
          this.listLoading = false
        })
      }
    },
    computed: {
      // 编辑管理员信息按钮是否显示
      editInfoButton() {
        return !util.isEmpty(isUrlHasPurview(this.$store.state, 'adminer/edit'))
      },
      // 删除管理员按钮是否显示
      deleteButton() {
        return !util.isEmpty(isUrlHasPurview(this.$store.state, 'adminer/delete'))
      },
      // 添加管理员按钮是否显示
      addButton() {
        return !util.isEmpty(isUrlHasPurview(this.$store.state, 'adminer/add'))
      },
      // 编辑管理员权限按钮是否显示
      editPurviewButton() {
        return !util.isEmpty(isUrlHasPurview(this.$store.state, 'adminer/editPurview'))
      }
    },
    created() {
      let _treePur = tree();
      for (let item in _treePur) {
        this.purviewList.push(item);
        this.purviewName.push(_treePur[item].name);
      }
      this.purviewTree = tree();
      this.getAdminers();
    }
  }

</script>
